package com.ruoyi.web.controller.module.customer;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.customer.domain.CustomerDistribution;
import com.ruoyi.customer.domain.CustomerUser;
import com.ruoyi.customer.service.ICustomerDistributionService;
import com.ruoyi.customer.service.ICustomerUserService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 客户分销信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/customer/distribution")
public class CustomerDistributionController extends BaseController
{
    @Autowired
    private ICustomerDistributionService customerDistributionService;

    @Autowired
    private ICustomerUserService customerUserService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 获取客户分销列表
     */
    @PostMapping("/customerDistributionList")
    public TableDataInfo list(@RequestBody CustomerDistribution customerDistribution, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            customerDistribution.setShopId(shopId);
        }
        startPageByPost();
        List<CustomerDistribution> list = customerDistributionService.selectUserList(customerDistribution);
        return getDataTable(list);
    }

    /**
     * 根据客户分销编号获取详细信息
     */
    @GetMapping("customerDistributionInfo")
    public AjaxResult customerDistributionInfo()
    {
        Long userId = SecurityUtils.getUserId();
        AjaxResult ajax = AjaxResult.success();
        CustomerDistribution customerDistribution = customerDistributionService.selectUserById(userId);
        ajax.put(AjaxResult.DATA_TAG, customerDistribution);
        return ajax;
    }

    /**
     * 根据客户分销编号获取详细信息
     */
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        CustomerDistribution customerDistribution = customerDistributionService.selectUserById(userId);
        ajax.put(AjaxResult.DATA_TAG, customerDistribution);
        return ajax;
    }

    /**
     * 新增客户分销 - 后台新增
     */
    @Log(title = "客户分销管理 - 新增", businessType = BusinessType.INSERT)
    @PostMapping("/customerDistributionInsert")
    public AjaxResult add(@Validated @RequestBody CustomerDistribution user, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            user.setShopId(shopId);
        }
        CustomerDistribution customerDistribution = customerDistributionService.selectUserById(user.getUserId());
        if (StringUtils.isNotNull(customerDistribution))
        {
            return error("新增失败：已经是分销者");
        }
        Long userId = SecurityUtils.getUserId();
        CustomerUser customerUser = customerUserService.selectUserById(userId);
        if (StringUtils.isNull(customerUser))
        {
            return error("新增失败：用户不存在");
        }
        return toAjax(customerDistributionService.insertUser(user));
    }

    /**
     * 新增客户分销 - 前台申请新增
     */
    @PostMapping("/customerDistributionApply")
    public AjaxResult customerDistributionApply(HttpServletRequest request)
    {
        Long userId = SecurityUtils.getUserId();
        CustomerDistribution customerDistribution = customerDistributionService.selectUserById(userId);
        if (StringUtils.isNotNull(customerDistribution))
        {
            return error("新增失败：已经是分销者");
        }
        CustomerDistribution cd = new CustomerDistribution();
        cd.setUserId(userId);
        String distributionRateStr = configService.selectConfigByKey("app.distribution.rate");
        String distributionModel = configService.selectConfigByKey("app.distribution.model");
        cd.setDistributionRate(Long.parseLong(distributionRateStr));
        cd.setDistributionModel(distributionModel);
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            cd.setShopId(shopId);
        }
        return toAjax(customerDistributionService.insertUser(cd));
    }

    /**
     * 修改客户分销
     */
    @PreAuthorize("@ss.hasPermi('customer:user:edit')")
    @Log(title = "客户分销管理 - 修改", businessType = BusinessType.UPDATE)
    @PostMapping("/customerDistributionUpdate")
    public AjaxResult edit(@Validated @RequestBody CustomerDistribution user)
    {
        user.setUpdateBy(getUsername());
        return toAjax(customerDistributionService.updateUser(user));
    }

    /**
     * 修改客户分销 - 客户修改
     */
    @Log(title = "客户分销管理 - 修改", businessType = BusinessType.UPDATE)
    @PostMapping("/customerDistributionUpdateInfo")
    public AjaxResult customerDistributionUpdateInfo(@Validated @RequestBody CustomerDistribution user)
    {
        Long userId = SecurityUtils.getUserId();
        CustomerDistribution cd = customerDistributionService.selectUserById(userId);
        cd.setUserId(userId);
        cd.setQrCode(user.getQrCode());
        cd.setWxId(user.getWxId());
        cd.setRealName(user.getRealName());
        return toAjax(customerDistributionService.updateUser(cd));
    }

    @Log(title = "客户分销管理 - 导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('customer:user:export')")
    @PostMapping("/customerDistributionExport")
    public void export(HttpServletResponse response, CustomerDistribution user)
    {
        List<CustomerDistribution> list = customerDistributionService.selectUserList(user);
        ExcelUtil<CustomerDistribution> util = new ExcelUtil<CustomerDistribution>(CustomerDistribution.class);
        util.exportExcel(response, list, "客户分销数据");
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('customer:user:edit')")
    @Log(title = "客户分销管理-状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/customerDistributionChangeActive")
    public AjaxResult changeActive(@RequestBody CustomerDistribution user)
    {
        user.setUpdateBy(getUsername());
        return toAjax(customerDistributionService.updateUserActive(user));
    }
}
